package com.hgkj.common.web.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.hgkj.common.core.constant.HttpStatusConstant;
import com.hgkj.common.core.domain.ApiResult;
import com.hgkj.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义异常
     */
    @ExceptionHandler(ServiceException.class)
    public ApiResult handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return ApiResult.error(e.getMessage());
    }

    // 处理方法参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 提取所有字段错误信息
        StringBuilder errorMsg = new StringBuilder("参数校验失败:");
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorMsg.append(fieldError.getDefaultMessage()).append(" ");
        }
        return ApiResult.error(errorMsg.toString());
    }

    // 处理请求参数校验异常（如 @PathVariable, @RequestParam）
    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResult handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder errorMsg = new StringBuilder("参数校验失败:");
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            errorMsg.append(constraintViolation.getMessage()).append(" ");
        }
        return ApiResult.error(errorMsg.toString());
    }
    @ExceptionHandler(NotLoginException.class)
    public ApiResult handleNotLoginException(NotLoginException e){
        return ApiResult.error(HttpStatusConstant.UNAUTHORIZED,e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ApiResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ApiResult.error(e.getMessage());
    }

}
